<?php
namespace App\Service\Command\Admin\System;

use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use App\Models\System\SystemAdminModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdminCommandService
{
    public function add($params)
    {
        DB::beginTransaction();
        try{

            $model = new SystemAdminModel();
            $model->fill($params)->save();
            $roleIds = explode(',',$params['role_ids']);
            $roles = [];
            foreach ($roleIds as $roleId) {
                $roles[$roleId] = ['created_at'=>Carbon::now()->toDateTimeString()];
            }

            $model->roles()->attach($roles);
            DB::commit();

            return JsonResult::returnJson(ResponseCode::SUCCESS);

        }catch (\Exception $exception) {
            DB::rollBack();
            return JsonResult::returnJson(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());

        }


    }

    public function update(SystemAdminModel $adminModel,$params)
    {
        DB::beginTransaction();

        try{
            $validateResult =  $this->updateValidate($adminModel,$params);

            if ( true !== $validateResult ) {
                return $validateResult;
            }

            foreach ($params as $key => $param) {
                if ( isset($adminModel->$key) ) {
                    $adminModel->$key = $param;
                }
            }
            $roleIds = explode(',',$params['role_ids']);
            $roles = [];
            foreach ($roleIds as $roleId) {
                $roles[$roleId] = ['created_at'=>Carbon::now()->toDateTimeString()];
            }

            $adminModel->save();
            $adminModel->roles()->detach();

            $adminModel->roles()->attach($roles);
            DB::commit();

            return JsonResult::returnJson(ResponseCode::SUCCESS);

        }catch (\Exception $exception) {
            DB::rollBack();
            return JsonResult::returnJson(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());

        }
    }

    /**
     * 更新校验
     * @param $user
     * @param $params
     * @return bool|\Illuminate\Http\JsonResponse
     */
    private function updateValidate($user,$params)
    {
        if ( $user->username != $params['username'] ) {
              if ( SystemAdminModel::whereUsername($params['username'])->exists() ) {
                  return JsonResult::returnJson(ResponseCode::USER_ALREADY_EXISTS);
              }
        }

        if ( $user->mobile != $params['mobile'] ) {
            if ( SystemAdminModel::whereMobile($params['mobile'])->exists() ) {
                return JsonResult::returnJson(ResponseCode::MOBILE_ALREADY_EXISTS);
            }
        }

        if ( $user->email != $params['email'] ) {
            if ( SystemAdminModel::whereEmail($params['email'])->exists() ) {
                return JsonResult::returnJson(ResponseCode::EMAIL_ALREADY_EXISTS);
            }
        }

        return true;
    }


    public function password($params)
    {
        $user = Auth::guard('admin')->user();

        if (  !Hash::check($params['old_password'],$user->password)  ) {
            return JsonResult::returnJson(ResponseCode::OLD_PASS_ERROR);
        }

        $user->password = bcrypt($params['password']);

        $user->save();
        Auth::guard('admin')->setUser($user);

        return JsonResult::returnJson(ResponseCode::SUCCESS);
    }

}